#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试Neo4j知识图谱问答功能
Test Neo4j Knowledge Graph QA functionality
"""

import os
import sys
import logging

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def test_neo4j_qa_basic():
    """基础测试，不依赖实际的Neo4j连接"""
    try:
        from api.models.medical_model import MedicalQAModel
        
        # 创建医疗模型实例（禁用Neo4j和深度学习以避免依赖问题）
        model = MedicalQAModel(use_deep_learning=False, use_neo4j=False)
        
        print("✓ 医疗模型创建成功")
        print(f"  - 疾病数量: {len(model.diseases_data)}")
        print(f"  - 科室数量: {len(model.departments_data)}")
        print(f"  - 使用Neo4j: {model.use_neo4j}")
        print(f"  - 使用深度学习: {model.use_deep_learning}")
        
        # 测试基础问答功能
        test_questions = [
            "感冒有什么症状？",
            "胃痛应该挂什么科？",
            "你好",
            "谢谢"
        ]
        
        print("\n--- 基础问答测试 ---")
        for question in test_questions:
            try:
                result = model.generate_answer(question)
                print(f"问题: {question}")
                print(f"答案: {result['answer']}")
                print(f"来源: {result['source']}")
                print(f"评分: {result['score']}")
                print("-" * 50)
            except Exception as e:
                print(f"问题 '{question}' 处理失败: {str(e)}")
        
        return True
        
    except Exception as e:
        print(f"✗ 基础测试失败: {str(e)}")
        return False

def test_neo4j_service_methods():
    """测试Neo4j服务方法是否正确定义"""
    try:
        from api.services.neo4j_service import Neo4jService
        
        # 创建服务实例（不实际连接）
        print("✓ Neo4j服务类导入成功")
        
        # 检查方法是否存在
        service = Neo4jService()
        
        required_methods = [
            'query_disease_symptoms',
            'query_symptom_diseases', 
            'query_disease_treatment',
            'query_department_recommendation',
            'query_drug_information',
            'query_complex_relationship'
        ]
        
        print("\n--- Neo4j服务方法检查 ---")
        for method in required_methods:
            if hasattr(service, method):
                print(f"✓ {method}")
            else:
                print(f"✗ {method} - 缺失")
        
        return True
        
    except Exception as e:
        print(f"✗ Neo4j服务测试失败: {str(e)}")
        return False

def test_knowledge_graph_query_methods():
    """测试知识图谱查询方法"""
    try:
        from api.models.medical_model import MedicalQAModel
        
        # 创建医疗模型实例
        model = MedicalQAModel(use_deep_learning=False, use_neo4j=False)
        
        print("\n--- 知识图谱查询方法测试 ---")
        
        # 测试问题分析方法
        test_questions = [
            ("感冒有什么症状？", "disease_symptoms"),
            ("发热可能是什么病？", "symptom_diseases"),
            ("感冒怎么治疗？", "disease_treatment"),
            ("胃痛应该挂什么科？", "department_recommendation"),
            ("阿司匹林的用法", "drug_information")
        ]
        
        for question, expected_type in test_questions:
            question_type, keywords = model._analyze_question(question)
            print(f"问题: {question}")
            print(f"  类型: {question_type} (期望: {expected_type})")
            print(f"  关键词: {keywords}")
            print()
        
        # 测试知识图谱答案生成（使用空结果）
        empty_kg_results = {
            'diseases': [],
            'symptoms': [],
            'drugs': [],
            'departments': [],
            'relationships': []
        }
        
        kg_answer = model._generate_knowledge_graph_answer("测试问题", empty_kg_results)
        print(f"空结果答案生成: {'成功' if isinstance(kg_answer, str) else '失败'}")
        
        return True
        
    except Exception as e:
        print(f"✗ 知识图谱查询方法测试失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def main():
    """主测试函数"""
    print("=== Neo4j知识图谱问答功能测试 ===\n")
    
    tests = [
        ("基础功能测试", test_neo4j_qa_basic),
        ("Neo4j服务方法测试", test_neo4j_service_methods),
        ("知识图谱查询方法测试", test_knowledge_graph_query_methods),
    ]
    
    passed = 0
    total = len(tests)
    
    for test_name, test_func in tests:
        print(f"\n=== {test_name} ===")
        try:
            if test_func():
                passed += 1
                print(f"✓ {test_name} 通过")
            else:
                print(f"✗ {test_name} 失败")
        except Exception as e:
            print(f"✗ {test_name} 异常: {str(e)}")
    
    print(f"\n=== 测试结果 ===")
    print(f"通过: {passed}/{total}")
    print(f"成功率: {(passed/total)*100:.1f}%")
    
    if passed == total:
        print("🎉 所有测试通过！Neo4j知识图谱问答功能实现成功！")
        return True
    else:
        print("❌ 部分测试失败，需要进一步修复")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)